import { Router } from "vue-router";
import { WHITE_NAME } from "/@/router";
import { userStore } from "/@/store/module/UserManager";
import { PageEnum } from "/@/enums/pageEnum";
import { routerStore } from "/@/store/module/RouterManager";


export function createPageGuard(router: Router) {
  router.beforeEach((to, from, next) => {
    if(WHITE_NAME.includes(to.name as string)){
      next();
      return;
    }
    if(!userStore.getAccessToken){
      // redirect login page
      const redirectData: { path: string; replace: boolean; query?: any } = {
        path: PageEnum.BASE_LOGIN,
        replace: true,
      };
      if (to.path) {
        redirectData.query = {
          ...redirectData.query,
          redirect: to.path,
        };
      }
      next(redirectData);
      return;
    }
    if (routerStore.getIsDynamicAddedRouteState) {
      next();
      return;
    }
    const redirectPath = (from.query.redirect || to.path) as string;
    const redirect = decodeURIComponent(redirectPath);
    routerStore.commitDynamicAddedRouteState(true);
    const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
    next(nextData);
  })
}
